var dataGrid;
$(function(){
	dataGrid = $('#dataGrid').datagrid({
		title:'用户列表',
		iconCls:'icon-tip',
		nowrap: false,
		striped: true,
		queryParams:{}, //查询条件  
		url: contextPath + '/user/getUserListData.action',
		sortName: 'createTime',
		sortOrder: 'desc',
		loadMsg:'数据加载中请稍后...', 
		remoteSort: false,
		idField:'id',
		fitColumns:true,
		/*singleSelect: true,*/
		pagination:true,
        rownumbers:true,
        scrollbarSize:0,
		columns:[[
            {field:'ck',checkbox:true},
            {title:'编号',field:'id',width:0.05,sortable:true,
            	sorter:function(a,b){
					return (a>b?1:-1);
				}
            },
			{title:'账号',field:'loginName',width:0.1,sortable:true},
			{title:'姓名',field:'realName',width:0.1,sortable:true},
			{title:'电子邮箱',field:'email',width:0.12,sortable:true},
			{title:'创建时间',field:'createTime',width:0.13,sortable:true},
			{title:'状态',field:'status',width:0.1,sortable:true,
				formatter:function(value,rowData){
					if("1" == value){
						return "正常";
					}else if("2" == value){
						return "锁定";
					}else{
						return "未知";
					}
				}
			},
			{title:'描述',field:'description',width:0.2,sortable:true},
			{field:'opt',title:'操作',width:0.2,align:'center',formatter:formatOperate}
		]],
		onLoadSuccess:function(){ 
			//一定要加上这一句，要不然datagrid会记住之前的选择状态，删除时会出问题
			$('#dataGrid').datagrid('clearSelections');
			//鼠标放上去提示信息
			$("#dataGrid").datagrid('tooltip',['description']);
		}  
	});
	
	$('#searchPanel').panel({  
		width:"100%",  
		height:"100%", 
		/*collapsible:true,*/
		title: '用户查询'
	});  
	
    // 当窗口大小发生变化时，调整DataGrid的大小  
    $(window).resize(function() { 
    	$('#searchPanel').panel('resize',{width:$(document.body).width() - 10});
        $('#dataGrid').resizeDataGrid(300);  
    });  
    
    //查询操作
    $("#queryUserBtn").click(function(){
        var queryUserForm = $("#queryUserForm").serializeArray();
		var queryParams = $('#dataGrid').datagrid('options').queryParams;
        $.each(queryUserForm, function(i, field){
            queryParams[field.name] = field.value;
        });
        //重新加载datagrid的数据  
        dataGrid.datagrid('load');
    });
    
    //添加用户
    $("#add-user-btn").click(function(){
    	dataGrid.datagrid('clearSelections');
    	showDialog("添加用户",contextPath + '/user/toAddUser.action');
    });
    
    //删除用户
    $("#delete-user-btn").click(function(){
    	var ids = [];
		var rows = dataGrid.datagrid('getSelections');
		if (rows.length == 0) {
        	parent.$.messager.alert('提示', '请选择要删除的记录!', 'info');
        	return;
    	}
    	for (var i = 0; i < rows.length; i++) {
        	ids.push(rows[i].id);
    	}
    	delUser(ids);
	});
});

function showDialog(title,url){
	parent.$.modalDialog({
		title : title,
		iconCls:"icon-tip",
		width:600,
		height:325,
		href : url,
		buttons:[{ 
			text : '确定',
			iconCls : 'icon-ok',
			handler : function() {
				parent.$.modalDialog.openner_dataGrid = dataGrid;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
				var f = parent.$.modalDialog.handler.find('#form');
				f.submit();
			}
		}, {
			text : '取消',
			iconCls : 'icon-cancel',
			handler : function() {
				parent.$.modalDialog.handler.dialog('close');
		   } 
		}]
	});
}

function editUser(userId){
	dataGrid.datagrid('clearSelections');
	showDialog("修改用户",contextPath+"/user/toEditUser.action?id="+userId);
}

//分配角色
function assignRoles(userId,loginName){
	var title = "给账号[ "+loginName+" ]分配角色";
	parent.$.modalDialog({
		title : title,
		iconCls:"icon-tip",
		width:600,
		height:380,
		href : contextPath + "/user/toAssignRoles.action?id="+userId
	});
}

function delUser(userIds){
	parent.$.messager.confirm('提示', '确定要删除吗？',function(r){
        if(r){
        	parent.$.messager.progress({
				title : '提示',
				text : '数据处理中，请稍后....'
			});
            $.ajax({
                url: contextPath+'/user/delUser.action',
                type: 'post',
                data: "userIds="+userIds,
                error: function(){
                	parent.$.messager.progress('close');
                	parent.$.messager.alert('提示','操作失败，请重新再试！','error');      
                },
                success: function(data){
                    if (data.result == 'success') {
                    	parent.$.messager.alert('提示',data.msg,'info');
                    	dataGrid.datagrid('reload');
                        dataGrid.datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
                    }else{
                    	$.messager.alert('提示',data.msg,'error');      
                    }
                    parent.$.messager.progress('close');
                }
            });
        }
    });
}